from django_filters import rest_framework as filters
from blog.models import Article, Tag, Category
from django.db.models import Q
from learn.models import Learn

class ArticleFilter(filters.FilterSet):
    # icontains 表示不区分大小写的包含
    title = filters.CharFilter(lookup_expr='icontains')
    category_id = filters.NumberFilter()
    article_type = filters.NumberFilter()
    tags = filters.CharFilter(method='filter_tags')
    # 关键字搜索 - 同时搜索标题和作者
    search = filters.CharFilter(method='filter_search')
    is_top = filters.BooleanFilter()
    slug = filters.CharFilter(lookup_expr='icontains')

    def filter_search(self, queryset, name, value):
        """同时搜索标题和作者名称"""
        if value:
            return queryset.filter(
                Q(title__icontains=value) | 
                Q(author__username__icontains=value)
            )
        return queryset

    def filter_tags(self, queryset, name, value):
        """支持多标签过滤"""
        if value:
            tag_ids = value.split(',')
            return queryset.filter(tags__id__in=tag_ids).distinct()
        return queryset

    class Meta:
        model = Article
        fields = ['title', 'category_id', 'article_type', 'tags', 'search',  'is_top','slug']


class LearnFilter(filters.FilterSet):
    category = filters.NumberFilter()
    
    class Meta:
        model = Learn
        fields = ['category']
    
